//
//  HomeBaseViewController.m
//  JxCarios
//
//  Created by xcq on 15/1/21.
//  Copyright (c) 2015年 xiongchuanqi. All rights reserved.
//

#import "HomeBaseViewController.h"
#import "CurrentDataSource.h"
#import "ConfigDefine.h"
#import "ReplaceDriveViewController.h"
#import "RoadsideAssistanceViewController.h"
#import "DrawTrailerTableViewController.h"
#import "WXCategoryViewController.h"
#import "ActicityShowDetailViewController.h"
#import "WXIllegalTableViewController.h"
#import "WXQuetyBreakTableViewController.h"
#import "ARefundViewController.h"
 #define MAINSCREEN [UIScreen mainScreen].bounds.size
#define MAINSCREENHEIGHT [UIScreen mainScreen].bounds.size.height
#define MAINSCREENWIDHT  [UIScreen mainScreen].bounds.size.width
#define PAGEVIEWHEIGHT 180
#define HORIZONTARSPACING 8
#define VERTICALSPACING 6
#define LOWWIDTHASPECTRATIO 2.5
#define HIGHTWIDTHASPECTRATIO 0.75

static BOOL methonIsRun = NO;

@interface HomeBaseViewController ()
@end

@implementation HomeBaseViewController

+ (instancetype)getInstance {
    HomeBaseViewController *base = [[HomeBaseViewController alloc] initWithNibName:@"HomeBaseViewController" bundle:nil];
    
     return base;
}

- (id)initWithCoder:(NSCoder *)aDecoder{
    self = [super  initWithCoder:aDecoder];
    return self;
}

-  (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
   self =  [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
     
    }
    return  self;
}

- (void)getPicture{
    methonIsRun = YES;
    if (!self.dataSource) {
        self.dataSource = [CurrentDataSource dataSourceWithRequestor:self];
    }
    if (_picArr && _picArr.count > 0) {
        return;
    }
   UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushActivity:)];
    [self.dataSource getHomeActivityPic:^(id result) {
        _activityInfo = [(NSDictionary *)result objectForKey:@"picinfo"];
        for (int i = 0; i < _activityInfo.count ; i ++) {
            UIImageView *imageV = [UIImageView new];
            [imageV setImageWithURL:[NSURL URLWithString:[_activityInfo[i] customObjectForkey:@"LOGO_URL"]] placeholderImage:nil options:SDWebImageProgressiveDownload];
            UIControl *contrl = [[UIControl alloc] initWithFrame:_pageView.bounds];
            contrl.tag = 300 + i;
            [contrl addTarget:self action:@selector(pushActivity:) forControlEvents:UIControlEventTouchUpInside];
            [imageV addSubview:contrl];
             imageV.userInteractionEnabled = YES;
             [_picArr addObject: imageV];
        }
        if (pageScrollView) {
            [pageScrollView setPageViews:_picArr];
            [pageScrollView shouldAutoShow:YES];
            [pageScrollView setPageNo:(int)[_picArr count]];;
        }else{
            [self setUpScrollView];
        }
        methonIsRun = NO;

    }andFail:^(id result) {
        
    }];
}

- (void)pushActivity:(UIControl *)sender {
    NSInteger tag =  sender.tag % 300;
    ActicityShowDetailViewController *activity = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ActicityShow"];
    activity.info = [[_activityInfo objectAtIndex:tag] copy];
    CLUIBaseNavigationController *base = [[CLUIBaseNavigationController alloc] initWithRootViewController:activity];
    [self presentViewController:base animated:YES completion:nil];
    
}

#pragma mark - 网络请求代理
-(void)networkingStartHandleWithRequestIdentifier:(RequestIdentifier)identifier
{
   
    
}

-(void)networkingCompleteHandleWithRequestIdentifier:(RequestIdentifier)identifier
{
    
}

-(void)networkingFailureHandleWithRequestIdentifier:(RequestIdentifier)identifier errorMessage:(NSString *)message
{

    
}

- (void)viewDidAppear:(BOOL)animated { 
    [self getPicture];
}

- (void)getWeather{
    if (!self.dataSource) {
        self.dataSource = [CurrentDataSource dataSourceWithRequestor:self];
    }
    if ([Common currenCity]) {
        self.dataSource.city = [[Common currenCity] customObjectForkey:@"city"];
        [self.dataSource getWeather:^(id result) {
            [self setUpWeatherAboutControls:result];
            [self setLocservice];
        } andFail:^(id result) {
            
        }];
     }else {
         [self setLocservice];
    }
    
}

- (void)setLocservice {
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        self.locationManager = [[CLLocationManager alloc] init];
        //获取授权认证
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager requestWhenInUseAuthorization];
    }
    
    if (!self.locService) {
        self.locService = [[LocationGetObj alloc] init];
    }
    self.locService.delegate = self;
    [self.locService startLocation];
 
}

- (void)getLocationSuccess:(BMKUserLocation *)userLocation{
   
    BMKReverseGeoCodeOption *geo = [[BMKReverseGeoCodeOption alloc] init];
    geo.reverseGeoPoint = userLocation.location.coordinate;
    self.locService.geoDelegate = self;
    (void)[self.locService startReverseGeoCode:geo];
    [self.locService stopLocation];
    
}
 

- (void)getLocationFail:(NSError *)error {
    NSLog(@"%@",error.localizedDescription);
    [self.locService stopLocation];

}

- (void)onGetReverseGeoCodeResultSuccess:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    NSMutableDictionary *dic = [NSMutableDictionary new];
    [dic setObject:result.addressDetail.district forKey:@"district"];
    [dic setObject:result.addressDetail.city forKey:@"city"];
    [dic setObject:result.addressDetail.province forKey:@"province"];
    NSDictionary *location = @{@"lat":@(result.location.latitude),@"lon":@(result.location.longitude)};
    [dic setObject:location forKeyedSubscript:@"location"];
    [Common setCurrenCity:dic];
    self.dataSource.city = [[Common currenCity] customObjectForkey:@"city"];
    [self.dataSource getWeather:^(id result) {
         [self setUpWeatherAboutControls:result];
 
    } andFail:^(id result) {
        
    }];
    
    
}

- (void)setUpWeatherAboutControls:(id)result {
    NSDictionary *weather = [result customObjectForkey:@"weather"];
    NSDictionary *weatherAbout = [[weather customObjectForkey:@"results"] firstObject];
    
    NSArray *weatherDetail = [weatherAbout customObjectForkey:@"index"];
    //洗车信息字典
    NSDictionary *xicheDetail = [weatherDetail objectAtIndex:1];
    
    //天气信息字典
    NSDictionary *weather_data = [[weatherAbout customObjectForkey:@"weather_data"] firstObject];
     _city_weather.text = [weatherAbout customObjectForkey:@"currentCity"];
    [_weatherImg setImageWithURL:[NSURL URLWithString:[weather_data customObjectForkey:@"dayPictureUrl"]] placeholderImage:nil];
    _AirTemperature.text = [@"气温:" stringByAppendingString:[weather_data customObjectForkey:@"temperature"]];
    _detail_weather.text = [@"天气:" stringByAppendingString:[weather_data customObjectForkey:@"weather"]];
    _windPower_weather.text =[@"风力风向:" stringByAppendingString:[weather_data customObjectForkey:@"wind"]];
    _carWash_weather.text = [@"洗车指数:"stringByAppendingString:[xicheDetail customObjectForkey:@"zs"]];
    _date.text = [weather customObjectForkey:@"date"];
    _weakNum.text = [[[weather_data customObjectForkey:@"date"] componentsSeparatedByString:@" "] firstObject];
    

}


- (void)viewDidLoad {
    [super viewDidLoad];
    _weatherView.backgroundColor = [UIColor colorWithRed:229/255 green:229/255 blue:229/255 alpha:0.3];
    _picArr = [NSMutableArray new];
    _activityInfo = [NSArray new];
    [self getWeather];

}



- (void)setUpScrollView{
    pageScrollView = [[PageView alloc] initWithFrame:_pageView.bounds];
  //  [pageScrollView pageControl];
    [pageScrollView shouldAutoShow:YES];
    [pageScrollView scrollView];
    [pageScrollView setPageViews:_picArr];
    [pageScrollView setPageNo:(int)[_picArr count]];;
    [pageScrollView hiddenPageControl];
    [_pageView addSubview:pageScrollView];
    
    _indicator = [[Indicator alloc] initWithFrame:CGRectMake(pageScrollView.frame.origin.x, pageScrollView.frame.size.height - 2, 0, 2) andPage:[_picArr count] and:self andBackGroundColor:BTN_COLOR];
    [_pageView addSubview:_indicator];
    [_indicator shouldAutoShow:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
  
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)wzcxAction:(id)sender {
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    if (![Common currenLoginStatus]) {
        int queryNum = [[[NSUserDefaults standardUserDefaults] objectForKey:@"queryNum"] intValue];
        if (queryNum <= 3) {
            WXQuetyBreakTableViewController *quety = [story instantiateViewControllerWithIdentifier:@"quetyBreak"];
            CLUIBaseNavigationController *base = [[CLUIBaseNavigationController alloc] initWithRootViewController:quety];
            [self presentViewController:base animated:YES completion:nil];
        }else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您未登录已查询3次，请登录后再查询" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去登录", nil];
            
            [alert show];
        }
    }else{
        
        WXIllegalTableViewController *illegal = [story instantiateViewControllerWithIdentifier:@"Illegal"];
        CLUIBaseNavigationController *base = [[CLUIBaseNavigationController alloc] initWithRootViewController:illegal ];
        [self presentViewController:base animated:YES completion:^{
            
        }];
        
    }
}

- (IBAction)ljAction:(id)sender {
    NSLog(@"%@",[self class]);
    RoadsideAssistanceViewController *road = [[RoadsideAssistanceViewController alloc] init];
    CLUIBaseNavigationController *nav = [[CLUIBaseNavigationController alloc] initWithRootViewController:road];
    [self presentViewController:nav animated:YES completion:^{
        
    }];
}
//代驾
- (IBAction)djAction:(id)sender {
  ReplaceDriveViewController *control = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"replaceDrive"];
    CLUIBaseNavigationController *nav = [[CLUIBaseNavigationController alloc] initWithRootViewController:control];
    [self presentViewController:nav animated:YES completion:^{

    }];
}
//拖车
- (IBAction)pullCar:(id)sender {
    DrawTrailerTableViewController *draw = [[DrawTrailerTableViewController alloc] init];
    CLUIBaseNavigationController *nav = [[CLUIBaseNavigationController alloc] initWithRootViewController:draw];
    [self presentViewController:nav animated:YES completion:^{
        
    }];
}
- (IBAction)carAround:(id)sender {
    WXCategoryViewController *category = [[WXCategoryViewController alloc] init];
    CLUIBaseNavigationController *nav = [[CLUIBaseNavigationController alloc] initWithRootViewController:category];
    [self presentViewController:nav animated:YES completion:nil];
    
}
@end
